package com.jiandan.plugin.module

import com.jiandan.plugin.http.HttpUtils
import com.jiandan.plugin.http.UploadProgress
import com.jiandan.plugin.http.UploadResult
import groovy.json.JsonSlurper

class PgyerUpload {

    void upload(String filePath, String pgyerApikey) {
        println("蒲公英上传-准备中: " + filePath)
        HttpUtils connectionUtil = new HttpUtils("https://www.pgyer.com/apiv2/app/upload", HttpUtils.HTTP_METHOD_POST)
        connectionUtil.addTextParameter("_api_key", pgyerApikey)
        connectionUtil.addFileParameter("file", new File(filePath))
        def lastResult = 0
        UploadResult uploadResult = connectionUtil.post(new UploadProgress() {
            @Override
            void onProgress(long hasWrite, long total) {
                double progress = hasWrite * 100.0 / total
                def progressInt = progress.toInteger()
                if (lastResult != progressInt) {
                    lastResult = progressInt
                    println("蒲公英上传进度：" + progressInt + "%")
                }
            }

            @Override
            void onResponseStart() {
                println("蒲公英上传结束 准备解析中")
            }
        })
        if (uploadResult.code != 200) {
            println("蒲公英上传失败 " + uploadResult.error)
            return
        }
        String result = uploadResult.response
        def data = new JsonSlurper().parseText(result)
        if (0 == data.code) {
            println("蒲公英上传成功 二维码: " + data.data.buildQRCodeURL)
        } else {
            println("蒲公英上传失败 详细信息如下: ")
            println(result)
        }
    }
}
